import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/tools_base/event_bus/event_bus_util.dart';
import 'package:xvideos/tools_base/event_bus/events.dart';

import '../../../hj_model/acg/CartoonMoreList.dart';
import '../../../hj_model/cartoon_media_info.dart';

typedef WidgetBuilder = Widget Function();

class CollectStatusWrapper extends StatefulWidget {
  final WidgetBuilder builder;
  final AllMediaInfo? allMediaInfo;
  final CartoonMediaInfo? mediaInfo;
  final VideoModel? videoModel;
  final TagsBean? tagModel;
  const CollectStatusWrapper({
    required this.builder,
    super.key,
    this.mediaInfo,
    this.allMediaInfo,
    this.videoModel,
    this.tagModel,
  });

  @override
  State<StatefulWidget> createState() {
    return _CollectStatusWrapperState();
  }
}

class _CollectStatusWrapperState extends State<CollectStatusWrapper> {
  late StreamSubscription subscription;
  @override
  void initState() {
    super.initState();
    subscription = eventBus.on<CollectStatusModel>(_listenCallback);
  }

  void _listenCallback(CollectStatusModel model) {
    String? obId = widget.allMediaInfo?.id ?? widget.mediaInfo?.id ?? widget.videoModel?.id ?? widget.tagModel?.id;
    //收藏和点赞逻辑
    if (obId == model.id && obId?.isNotEmpty == true) {
      if (model.isCollected != null) {
        widget.allMediaInfo?.mediaStatus?.hasCollected = model.isCollected;
        widget.mediaInfo?.mediaStatus?.hasCollected = model.isCollected;
        widget.videoModel?.vidStatus?.hasCollected = model.isCollected;
        widget.tagModel?.hasCollected = model.isCollected;
        setState(() {});
      } else if (model.isLiked != null) {
        widget.allMediaInfo?.mediaStatus?.hasLiked = model.isLiked;
        widget.mediaInfo?.mediaStatus?.hasLiked = model.isLiked;
        widget.videoModel?.vidStatus?.hasLiked = model.isLiked;
        setState(() {});
      } else {}
    }
    // 用户关注逻辑
    if (model.isFollowed != null && model.uid == widget.videoModel?.publisher?.uid) {
      widget.videoModel?.publisher?.hasFollowed = model.isFollowed;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder();
  }

  @override
  void dispose() {
    eventBus.off(subscription);
    super.dispose();
  }
}
